<template>
  <div class="bill-generation-page">
    <!-- 1. 操作与配置区 -->
    <el-card shadow="never" class="action-card">
      <template #header>
        <div class="card-header">
          <el-icon><DocumentAdd /></el-icon>
          <span>账单生成操作</span>
        </div>
      </template>
      <el-form :model="form" ref="formRef" label-width="100px" class="generation-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="10">
            <el-form-item 
              label="选择账期" 
              prop="billMonth"
              :rules="[{ required: true, message: '请选择要生成账单的月份', trigger: 'change' }]"
            >
              <el-date-picker
                v-model="form.billMonth"
                type="month"
                placeholder="选择月份"
                format="YYYY-MM"
                value-format="YYYY-MM"
                :disabled-date="disabledDate"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="14">
            <el-form-item label-width="0">
              <el-button 
                type="primary" 
                @click="handleGenerateBills" 
                :loading="generating" 
                :icon="Promotion"
              >
                {{ generating ? '正在生成中...' : '生成月度账单' }}
              </el-button>
              <el-button @click="resetForm" :icon="Refresh">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-alert
        title="操作提示"
        type="info"
        description="选择月份后，系统将为所有“在住”状态的老人自动计算当月费用（包括床位、护理、药品等），生成待确认的账单列表。"
        :closable="false"
        show-icon
        class="mt-4"
      />
    </el-card>

    <!-- 2. 账单预览与确认区 -->
    <el-card shadow="never" class="preview-card" v-if="previewList.length > 0">
      <template #header>
        <div class="card-header">
          <el-icon><View /></el-icon>
          <span>账单预览与确认</span>
        </div>
      </template>
      <div class="preview-actions">
        <el-alert 
          :title="`已成功生成 ${previewList.length} 份账单草稿，请仔细核对后进行最终确认。`" 
          type="success" 
          :closable="false"
          show-icon
        />
        <el-button 
          type="success" 
          @click="handleConfirmAll" 
          :loading="confirming"
          :disabled="!previewList.length"
          :icon="Select"
        >
          {{ confirming ? '正在确认...' : '全部确认并发送' }}
        </el-button>
      </div>
      <el-table :data="previewList" stripe border class="mt-4" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="elderly_name" label="老人姓名" width="120" />
        <el-table-column prop="bill_month" label="账单月份" width="120" align="center" />
        <el-table-column prop="total_amount" label="总金额 (元)" align="right" width="150">
          <template #default="{ row }">
            <span style="color: #F56C6C; font-weight: bold;">¥ {{ parseFloat(row.total_amount).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="warning">{{ statusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" align="center" fixed="right">
          <template #default="{ row, $index }">
            <el-button text type="primary" size="small" :icon="View" @click="handleViewDetails(row)">详情</el-button>
            <el-button text type="warning" size="small" :icon="EditPen" @click="handleAdjustBill(row)">调整</el-button>
            <el-button text type="danger" size="small" :icon="Delete" @click="handleDiscardBill(row, $index)">作废</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 3. 历史生成记录 -->
    <el-card shadow="never" class="history-card">
      <template #header>
        <div class="card-header">
          <el-icon><Finished /></el-icon>
          <span>历史生成记录</span>
        </div>
      </template>
       <el-table :data="historyList" stripe border v-loading="loading">
        <el-table-column prop="generation_date" label="生成日期" width="180" align="center" />
        <el-table-column prop="bill_month" label="账单月份" width="120" align="center" />
        <el-table-column prop="operator_name" label="操作员" width="120" />
        <el-table-column prop="bill_count" label="生成数量" width="100" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 账单详情抽屉 -->
    <el-drawer v-model="drawerVisible" title="账单草稿详情" direction="rtl" size="50%">
      <div v-if="currentBill" class="drawer-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="老人姓名">{{ currentBill.elderly_name }}</el-descriptions-item>
          <el-descriptions-item label="账单月份">{{ currentBill.bill_month }}</el-descriptions-item>
          <el-descriptions-item label="状态">
             <el-tag type="warning">{{ statusText(currentBill.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            <strong style="color: #F56C6C;">¥ {{ parseFloat(currentBill.total_amount).toFixed(2) }}</strong>
          </el-descriptions-item>
        </el-descriptions>
        <h4 class="drawer-sub-title">费用明细</h4>
        <el-table :data="currentBill.details" border size="small" show-summary>
          <el-table-column prop="item_description" label="费用描述" />
          <el-table-column prop="amount" label="金额 (元)" align="right" width="120">
            <template #default="{ row }">
              <span>¥ {{ parseFloat(row.amount).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
       <template #footer>
        <div style="text-align: right;">
          <el-button @click="drawerVisible = false">关闭</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { DocumentAdd, Promotion, Refresh, View, EditPen, Delete, Finished, Select } from '@element-plus/icons-vue';

// --- state ---
const formRef = ref(null);
const form = reactive({
  billMonth: '',
});
const generating = ref(false);
const confirming = ref(false);
const loading = ref(false);
const previewList = ref([]);
const historyList = ref([]);
const drawerVisible = ref(false);
const currentBill = ref(null);

// --- mock data & api ---
// 模拟后端API调用
const api = {
  // 模拟生成账单
  generateBills: (month) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 检查是否已经为该月生成过（在真实后端完成）
        if (historyList.value.some(h => h.bill_month === month)) {
          return reject(new Error(`月份 ${month} 的账单已生成过，请勿重复操作。`));
        }
        // 模拟生成数据
        const generatedData = [
          { id: Date.now() + 1, elderly_user_id: 1, elderly_name: '张三', bill_month: month, total_amount: 4850.00, status: 'pending_confirmation', details: [{ item_description: '单人房床位费', amount: 3000 }, { item_description: '一级护理费', amount: 1500 }, { item_description: '药品-降压药', amount: 350 }] },
          { id: Date.now() + 2, elderly_user_id: 2, elderly_name: '李四', bill_month: month, total_amount: 4200.00, status: 'pending_confirmation', details: [{ item_description: '双人房床位费', amount: 2000 }, { item_description: '二级护理费', amount: 2200 }] },
          { id: Date.now() + 3, elderly_user_id: 3, elderly_name: '王五', bill_month: month, total_amount: 3000.00, status: 'pending_confirmation', details: [{ item_description: '基础床位费', amount: 1800 }, { item_description: '三级护理费', amount: 1200 }] },
        ];
        resolve(generatedData);
      }, 1500);
    });
  },
  // 模拟确认账单
  confirmBills: (billIds) => {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log('Confirming bill IDs:', billIds);
        resolve({ success: true, message: '账单已确认并发送给用户。' });
      }, 1000);
    });
  },
  // 模拟获取历史记录
  fetchHistory: () => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve([
          { id: 1, generation_date: '2023-11-01 10:00:00', bill_month: '2023-10', operator_name: '财务A', bill_count: 35, status: '已完成' },
          { id: 2, generation_date: '2023-10-01 09:30:00', bill_month: '2023-09', operator_name: '财务A', bill_count: 34, status: '已完成' },
        ]);
      }, 500);
    });
  }
};

// --- methods ---
const statusText = (status) => ({
  'pending_confirmation': '待确认',
  'unpaid': '未支付',
  'paid': '已支付',
  'overdue': '已逾期',
  'void': '已作废',
})[status] || '未知';

const disabledDate = (time) => {
  // 只能生成过去月份的账单，不能生成未来月份
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() > today.getTime();
};

const resetForm = () => {
  formRef.value?.resetFields();
  previewList.value = [];
};

const handleGenerateBills = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      generating.value = true;
      try {
        const data = await api.generateBills(form.billMonth);
        previewList.value = data;
        ElMessage.success(`成功生成 ${data.length} 份账单草稿！`);
      } catch (error) {
        ElMessage.error(error.message || '账单生成失败，请联系管理员。');
      } finally {
        generating.value = false;
      }
    }
  });
};

const handleConfirmAll = () => {
  ElMessageBox.confirm(
    `确定要将这 ${previewList.value.length} 份账单全部确认并发送吗？此操作不可逆。`, 
    '批量确认', 
    { confirmButtonText: '确定发送', cancelButtonText: '取消', type: 'warning' }
  ).then(async () => {
    confirming.value = true;
    const billIds = previewList.value.map(bill => bill.id);
    try {
      await api.confirmBills(billIds);
      ElMessage.success('所有账单已确认成功！');
      // 更新历史记录
      historyList.value.unshift({
        id: Date.now(),
        generation_date: new Date().toLocaleString(),
        bill_month: form.billMonth,
        operator_name: '当前管理员', // 从用户信息中获取
        bill_count: previewList.value.length,
        status: '已完成'
      });
      previewList.value = []; // 清空预览列表
    } catch (error) {
      ElMessage.error('确认失败，请重试。');
    } finally {
      confirming.value = false;
    }
  }).catch(() => {
    ElMessage.info('操作已取消');
  });
};

const handleViewDetails = (row) => {
  currentBill.value = JSON.parse(JSON.stringify(row));
  drawerVisible.value = true;
};

const handleAdjustBill = (row) => {
  ElMessage.info('调整功能正在开发中，将允许您编辑账单明细。');
};

const handleDiscardBill = (row, index) => {
  ElMessageBox.confirm(
    `确定要作废老人【${row.elderly_name}】的这份账单草稿吗？`,
    '作废草稿',
    { confirmButtonText: '确定作废', cancelButtonText: '取消', type: 'danger' }
  ).then(() => {
    previewList.value.splice(index, 1);
    ElMessage.success(`【${row.elderly_name}】的账单草稿已作废。`);
  }).catch(() => {});
};

const loadHistory = async () => {
  loading.value = true;
  try {
    historyList.value = await api.fetchHistory();
  } catch (error) {
    ElMessage.error('历史记录加载失败。');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  // 设置默认月份为上个月
  const lastMonth = new Date();
  lastMonth.setMonth(lastMonth.getMonth() - 1);
  form.billMonth = `${lastMonth.getFullYear()}-${String(lastMonth.getMonth() + 1).padStart(2, '0')}`;
  
  loadHistory();
});
</script>

<style lang="scss" scoped>
.bill-generation-page {
  flex-grow: 1;
display: flex;
flex-direction: column;
transition: none; /* 先移除过渡效果 */
background: #fafbfc;
width: 0; /* 重要：让flex-grow生效 */
}

.el-card {
  border-radius: 8px;
  border: none;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
  .el-icon {
    margin-right: 8px;
  }
}

.generation-form .el-button {
  margin-right: 10px;
}

.preview-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.drawer-sub-title {
  margin: 24px 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.drawer-content {
  padding: 0 10px;
}

@media (max-width: 768px) {
  .preview-actions {
    flex-direction: column;
    align-items: stretch;
  }
  .el-drawer {
    --el-drawer-size: 90% !important;
  }
}
</style>